<script setup lang="ts">
	import { useCorps } from "./utils/hook";
	import Refresh from "@iconify-icons/ep/refresh";
	import AddFill from "@iconify-icons/ri/add-circle-line";
  import More from "@iconify-icons/ep/more-filled";
	import { PureTableBar } from "@/components/RePureTableBar";
	import { useRenderIcon } from "@/components/ReIcon/src/hooks";
	import { reactive, ref } from "vue";
  import { message } from "@/utils/message";
  import { baseUrlApi } from "@/api/utils";
  import { getToken, formatToken } from "@/utils/auth";
  import { emitter } from "@/utils/mitt";
  import Printpage from "@/common/printpage.vue";
  import { purchaseOrderExportApi } from "@/api/purchaseOrderApi"
  import dayjs from "dayjs";
  import { Plus } from '@element-plus/icons-vue';
  import type { UploadInstance } from 'element-plus'
  import axios from "axios";
	const {
		form,
		loading,
		columns,
		dataList,
		pagination,
		isShow,
		onSearch,
		resetForm,
		openDialog,
		handleSizeChange,
		handleCurrentChange,
		deviceDetection,
		handleDelete,
    expandColumns,
    companySelect,
    supplierSelect,
    sortChange
	} = useCorps();
	const formRef = ref();



  const fileList = ref()
  const orderTypeSelect = [
    { value: 1, label: '采购入库'},
    { value: 2, label: '产品入库'},
    { value: 3, label: '产品退库'},
    { value: 4, label: '其他入库'},
    { value: 5, label: '生产退料'}
  ]
  const statusSelect = [
    { value: 1, label: '待执行'},
    { value: 2, label: '已执行'},
    { value: 3, label: '已废止'},
  ]
  const data = getToken();
  const actionUrl = baseUrlApi + "/purchaseOrder/import";
  const headers = { Authorization: 'Bearer ' + data.accessToken };
  const handleUploadSuccess = (res: any, file: any, fileList: any) => {
    isUploading.value = false;
    if (res.code === 200) {
      message(res?.msg || '导入成功', {
        type: "success"
      });
      onSearch()
    } else {
      message(res?.msg ?? "操作失败,请联系管理员", {
        type: "error"
      });
    }
    importDialog.value = false
  }
  const handleOnChange = (uploadFile: any, uploadFiles: any) => {
    console.log(uploadFile, uploadFiles)
    fileList.value = [];
    const blob = new Blob([uploadFile], {
      type: "application/x-msdownload",
    });
    let url = URL.createObjectURL(blob);
    fileList.value.push({
      name: uploadFile.name,
      url: url,
    })
    // fileList.value.push(uploadFile.raw)
  }
  const beforeUpload = (file) => {
    // 检查文件大小，这里以500MB为例
    const isLt500M = file.size / 1024 / 1024 < 500;
    if (!isLt500M) {
      message('上传文件大小不能超过 500MB!', {
        type: "warning"
      });
      return false;
    }
    isUploading.value = true; // 开始上传时显示加载状态
    return true; // 返回true允许上传继续进行
  };
  const handleUploadError = (error) => {
    isUploading.value = false;
    message(error, {
      type: "error",
      duration: 2500
    });
  }
  const customUpload = async (options) => {
    try {
      const formData = new FormData();
      formData.append('file', options.file);
      formData.append('orderType', options.data.orderType);
      formData.append('updateToStore', options.data.updateToStore);
      const res = await axios.post(baseUrlApi + '/purchaseOrder/import', formData, {
        headers: headers
      });
      options.onSuccess(res.data);
      message('上传成功', {
        type: "success"
      });
      onSearch()
    } catch (err) {
      options.onError(err);
      message(`上传失败: ${err.response?.data?.msg || err.msg}`, {
        type: "error",
        duration: 3000
      });
    }
    importDialog.value = false
    isUploading.value = false;
  };
  const importDialog = ref(false);
  const dialogForm = reactive({
    orderType: 1,
    updateToStore: 0
  })
  const importOrder = () => {
    importDialog.value = true
  }
  const isUploading = ref(false)
  const changJurictionFormData = (row, index) => {
    if(index === 2) {
      exportPurchaseOrder({
        purchaseOrderIds: [row.purchaseOrderId]
      })
    } else {
      let printcontrats = {
        printinfos: row,
        printinfoid: 5,
        printinfosstuas: true,
        componname: '',
      };
      emitter.emit("printinfos", printcontrats);
    }

  }
  const multipleSelect = ref([])
  const selectionChange = (val: any) => {

    multipleSelect.value = val;
  }
  const multipleExport = () => {
    if(multipleSelect.value.length > 0) {
      let arr = []
      for (let item of multipleSelect.value) {
        arr.push(item.purchaseOrderId)
      }
      exportPurchaseOrder({
        purchaseOrderIds: arr
      })
    } else {
      message('请选择要导出的数据', {
        type: "warning"
      });
    }
  }
  const exportPurchaseOrder = (params: any) => {
    purchaseOrderExportApi(params).then((res: any) => {
      const elink = document.createElement("a");
      elink.download = "入库单导出-" + dayjs().format('YYYYMMDDHHmmss') +".xls";
      elink.style.display = "none";
      const blob = new Blob([res], {
        type: "application/x-msdownload",
      });
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    })
  }
  const uploadRef = ref<UploadInstance>();
  const submitUpload = () => {
    uploadRef.value!.submit();
    fileList.value = [];
  }
  const handleTemplateDownload = () => {
    const a = document.createElement('a')  // 创建一个<a />标签
      // 设置下载文件地址（英文）
      // 如果文件直接是在 public文件下就直接写adminCeshi.xlsx
      // 如果有多级 public/template 则 template/adminCeshi.xlsx
    a.href = '入库信息模版.xlsx'
    a.download = '入库信息模版.xls' // 设置下载文件名
    a.style.display = 'none' // 隐藏a标签
    document.body.appendChild(a)  // 将a标签追加到文档对象中
    a.click()   // 点击，浏览器自动下载
    a.remove()  // 用完就删除<a />标签
  }
  //合计
  const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '合计';
        return;
      }
      const values = data.map(item => Number(item[column.property]));
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if(column.property === 'number') {
            return prev + curr;
          } else if(column.property === 'amount') {
            return prev + curr;
          } else {
            return '--'
          }
        }, 0);
        // sums[index] += '';
      } else {
        sums[index] = '--';
      }
    });
    return sums;
  };
</script>

<template>
	<div class="main">
		<el-form ref="formRef" :inline="true" :model="form"
			class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
			<el-form-item label="入库单号:">
				<el-input v-model="form.orderNo" class="!w-[180px]" clearable placeholder="请输入" />
			</el-form-item>
			<el-form-item label="供应商:">
        <el-select v-model="form.supplierId" class="!w-[180px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in supplierSelect"
            :key="item.supplierId"
            :value="item.supplierId"
            :label="item.supplierName"
          />
        </el-select>
			</el-form-item>
      <el-form-item label="单据类型:">
        <el-select v-model="form.orderType" class="!w-[110px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in orderTypeSelect"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态:">
        <el-select v-model="form.status" class="!w-[100px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in statusSelect"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库单日期:">
        <!-- <el-date-picker v-model="form.orderDate" type="date" placeholder="请选择" clearable style="width: 180px" format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" /> -->
        <el-date-picker v-model="form.dateRange" type="daterange" placeholder="请选择" clearable style="width: 350px" format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item label="所属公司:">
        <el-select v-model="form.companyId" class="!w-[180px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in companySelect"
            :key="item.companyId"
            :value="item.companyId"
            :label="item.companyName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关键词:">
      	<el-input v-model="form.keyword" class="!w-[180px]" clearable placeholder="请输入" />
      </el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="useRenderIcon('ri:search-line')" :loading="loading" @click="onSearch">
					搜索
				</el-button>
				<el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
					重置
				</el-button>
			</el-form-item>
		</el-form>

		<div ref="contentRef" :class="['flex', deviceDetection() ? 'flex-wrap' : '']">
			<PureTableBar :class="[isShow && !deviceDetection() ? '!w-[60vw]' : 'w-full']"
				style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)" title=" " :columns="columns"
				@refresh="onSearch">
        <template #title>
          <el-button @click="multipleExport()">
          	批量导出
          </el-button>
        </template>
				<template #buttons>
          <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="openDialog()">
          	创建订单
          </el-button>
					<el-button @click="handleTemplateDownload">
						下载模板
					</el-button>
          <el-button @click="importOrder()">
          	导入数据
          </el-button>
				</template>
				<template v-slot="{ size, dynamicColumns }">
					<pure-table ref="tableRef" showOverflowTooltip table-layout="auto"
						:loading="loading" :size="size" adaptive :adaptiveConfig="{ offsetBottom: 108 }"
						:data="dataList" :columns="dynamicColumns" :pagination="pagination" @sort-change="sortChange" @selection-change="selectionChange"
						:paginationSmall="size === 'small' ? true : false" :header-cell-style="{background: 'var(--el-fill-color-light)',
						color: 'var(--el-text-color-primary)'}" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
            <template #expand="props">
              <pure-table ref="tableRef" align-whole="center" showOverflowTooltip table-layout="auto" border :summary-method="getSummaries" show-summary
                :adaptiveConfig="{ offsetBottom: 108 }" :data="props.row.orderProducts" :columns="expandColumns"
                :paginationSmall="true" :header-cell-style="{background: '#e3e3e3', color: 'var(--el-text-color-primary)'}">

              </pure-table>
            </template>
            <template #statusName="scope">
              <el-tag v-if="scope.row.status === 1" type="warning">{{scope.row.statusName}}</el-tag>
              <el-tag v-if="scope.row.status === 2">{{scope.row.statusName}}</el-tag>
              <el-tag v-if="scope.row.status === 3" type="danger">{{scope.row.statusName}}</el-tag>
            </template>
						<template #operation="{ row }">
              <el-button class="reset-margin" link type="primary" :size="size" @click="openDialog('执行', row)" v-if="row.status === 1">
              	执行
              </el-button>
              <el-button link type="primary" @click="changJurictionFormData(row, 2)" v-if="row.status === 2">导出</el-button>
              <el-button link type="primary" @click="changJurictionFormData(row, 1)">打印</el-button>

              <el-button class="reset-margin" link type="primary" :size="size" @click="openDialog('订单详情', row)">
              	详情
              </el-button>


              <el-dropdown>
                <el-button
                  class="ml-3 mt-[2px]"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(More)"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="row.status === 1" @click="openDialog('编辑订单', row)">
                      <el-button class="reset-margin" link type="primary" :size="size">
                      	编辑
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(row)" v-if="row.status !== 2">
                      <el-button class="reset-margin" link type="primary" :size="size">
                      	删除
                      </el-button>
                    </el-dropdown-item>

                    <el-dropdown-item @click="openDialog('2',row)" v-if="row.status === 2">
                      <el-button class="reset-margin" link type="primary" :size="size">
                      	废止
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
						</template>
					</pure-table>
				</template>
			</PureTableBar>
		</div>
    <Printpage />
    <el-dialog title="导入设置" v-model="importDialog" width="400px" draggable :close-on-click-modal="false">
      <el-form>
        <el-form-item label="单据类型:" required>
          <el-select v-model="dialogForm.orderType" class="!w-[180px]" placeholder="请选择">
            <el-option
              v-for="item in orderTypeSelect"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行入库:" required>
          <el-radio-group v-model="dialogForm.updateToStore" >
            <el-radio :value="0">否</el-radio>
            <el-radio :value="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传文件:" required>
          <!-- <el-upload
            ref="uploadRef"
            :action="actionUrl"
            accept=".xls, .xlsx"
            :on-success="handleUploadSuccess"
            :on-change="handleOnChange"
            :on-error="handleUploadError"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :file-list="fileList"
            v-loading="isUploading"
            :headers="headers"
            :data="{
              orderType: dialogForm.orderType,
              updateToStore: dialogForm.updateToStore,
            }"
            drag
            style="width: 100%;"
          >
            <template #trigger>
              <el-icon><Plus /></el-icon>
            </template>
          </el-upload> -->
          <el-upload
              ref="uploadRef"
              class="upload-demo"
              :action="actionUrl"
              accept=".xls, .xlsx"
              :auto-upload="false"
              drag
              :file-list="fileList"
              v-loading="isUploading"
              :headers="headers"
              :http-request="customUpload"
              :data="{
                orderType: dialogForm.orderType,
                updateToStore: dialogForm.updateToStore,
              }"
              style="width: 100%;"
            >
              <template #trigger>
                <el-icon><Plus /></el-icon>
              </template>
            </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer flex" style="justify-content: flex-end;">
          <el-button @click="importDialog = false">取 消</el-button>

          <el-button type="primary" @click="submitUpload">确 定</el-button>
        </span>
      </template>
    </el-dialog>
	</div>
</template>

<style scoped lang="scss">
	.main-content {
		margin: 10px 10px 0 !important;
	}
</style>
